package net.linlan.plat.comm.service;

import net.linlan.man.admin.dto.AdminUserDto;
import net.linlan.man.admin.service.AdminMenuEntService;
import net.linlan.man.admin.service.AdminRoleEntService;
import net.linlan.sys.role.entity.SysRole;
import net.linlan.sys.web.KernelConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 * 
 * @author Linlan
 */
@Component
public class SysPermissionService
{
    @Autowired
    private AdminRoleEntService sysRoleService;

    @Autowired
    private AdminMenuEntService sysMenuService;

    /**
     * 获取角色数据权限
     * 
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(AdminUserDto user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(sysRoleService.selectRoleCodeByAdminId(user.getId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(AdminUserDto user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    //status 0正常1停用2已删除
                    if (role.getStatus() != null && role.getStatus() == KernelConstant.DEFAULT_INT)
                    {
                        Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(role.getId());
                        perms.addAll(rolePerms);
                    }
                }

            }
            else
            {
                perms.addAll(sysMenuService.selectMenuPermsByAdminId(user.getId()));
            }
        }
        return perms;
    }
}
